<template>
  <div class="p-2">
    <!-- 消息管理 - MQTT主题管理 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
        <el-form-item label="主题名称" prop="topicName">
          <el-input v-model="queryParams.topicName" placeholder="请输入主题名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="主题类型" prop="topicType">
          <el-select v-model="queryParams.topicType" placeholder="请选择主题类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="系统主题" value="system" />
            <el-option label="设备主题" value="device" />
            <el-option label="用户主题" value="user" />
            <el-option label="广播主题" value="broadcast" />
          </el-select>
        </el-form-item>
        <el-form-item label="QoS等级" prop="qosLevel">
          <el-select v-model="queryParams.qosLevel" placeholder="请选择QoS等级" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="QoS 0" value="0" />
            <el-option label="QoS 1" value="1" />
            <el-option label="QoS 2" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增主题</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Upload" @click="handleImport">导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Message" @click="handlePublish" :disabled="single">发布消息</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="View" @click="handleSubscribe" :disabled="single">订阅监听</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Setting" @click="handlePermission" :disabled="single">权限设置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" :data="topicList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主题图标" width="100" align="center">
          <template #default="scope">
            <div class="topic-icon">
              <el-icon size="30" :color="getTopicIconColor(scope.row.topicType)">
                <component :is="getTopicIcon(scope.row.topicType)" />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="主题名称" prop="topicName" width="250" show-overflow-tooltip>
          <template #default="scope">
            <el-link type="primary" @click="handleView(scope.row)">{{ scope.row.topicName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="主题类型" prop="topicType" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getTopicTypeTag(scope.row.topicType)">{{ getTopicTypeText(scope.row.topicType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="QoS等级" prop="qosLevel" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getQosTag(scope.row.qosLevel)" size="small">QoS {{ scope.row.qosLevel }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="订阅数" prop="subscriberCount" width="100" align="center">
          <template #default="scope">
            <el-link type="primary" @click="viewSubscribers(scope.row)">{{ scope.row.subscriberCount }}个</el-link>
          </template>
        </el-table-column>
        <el-table-column label="消息数" prop="messageCount" width="100" align="center">
          <template #default="scope">
            <el-link type="success" @click="viewMessages(scope.row)">{{ scope.row.messageCount }}条</el-link>
          </template>
        </el-table-column>
        <el-table-column label="最后消息时间" prop="lastMessageTime" width="160" show-overflow-tooltip />
        <el-table-column label="保留消息" prop="retainMessage" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.retainMessage ? 'success' : 'info'" size="small">
              {{ scope.row.retainMessage ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权限控制" prop="accessControl" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.accessControl ? 'warning' : 'success'" size="small">
              {{ scope.row.accessControl ? '受限' : '开放' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="160" show-overflow-tooltip />
        <el-table-column label="描述" prop="description" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="发布消息" placement="top">
              <el-button link type="success" icon="Message" @click="handlePublish(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="订阅监听" placement="top">
              <el-button link type="warning" icon="Monitor" @click="handleSubscribe(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="权限设置" placement="top">
              <el-button link type="info" icon="Setting" @click="handlePermission(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="消息历史" placement="top">
              <el-button link type="primary" icon="Clock" @click="viewMessages(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 引入对话框组件 -->
    <TopicFormDialog
      :dialog="dialog"
      :form="form"
      :rules="rules"
      :activeTab="activeTab"
      @update:dialog="(val) => Object.assign(dialog, val)"
      @update:form="(val) => Object.assign(form, val)"
      @update:activeTab="activeTab = $event"
      @submit="submitForm"
      @cancel="cancel"
    />

    <TopicDetailDialog
      :detailDialog="detailDialog"
      :getTopicTypeTag="getTopicTypeTag"
      :getTopicTypeText="getTopicTypeText"
      :getQosTag="getQosTag"
      @update:detailDialog="(val) => Object.assign(detailDialog, val)"
    />

    <PublishMessageDialog
      :publishDialog="publishDialog"
      :publishForm="publishForm"
      :publishing="publishing"
      @update:publishDialog="(val) => Object.assign(publishDialog, val)"
      @update:publishForm="(val) => Object.assign(publishForm, val)"
      @publish="publishMessage"
      @cancel="publishDialog.visible = false"
    />

    <SubscribeDialog
      :subscribeDialog="subscribeDialog"
      :subscribeForm="subscribeForm"
      :subscribing="subscribing"
      :receivedMessages="receivedMessages"
      :getQosTag="getQosTag"
      @update:subscribeDialog="(val) => Object.assign(subscribeDialog, val)"
      @update:subscribeForm="(val) => Object.assign(subscribeForm, val)"
      @startSubscribe="startSubscribe"
      @stopSubscribe="stopSubscribe"
      @clearMessages="clearMessages"
    />

    <PermissionDialog
      :permissionDialog="permissionDialog"
      :permissionForm="permissionForm"
      @update:permissionDialog="(val) => Object.assign(permissionDialog, val)"
      @update:permissionForm="(val) => Object.assign(permissionForm, val)"
      @save="savePermission"
      @cancel="permissionDialog.visible = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download, Upload, Message, View, Monitor, Setting, Clock } from '@element-plus/icons-vue'
import { ChatDotSquare, Bell, Connection } from '@element-plus/icons-vue'
import TopicFormDialog from './components/TopicFormDialog.vue'
import TopicDetailDialog from './components/TopicDetailDialog.vue'
import PublishMessageDialog from './components/PublishMessageDialog.vue'
import SubscribeDialog from './components/SubscribeDialog.vue'
import PermissionDialog from './components/PermissionDialog.vue'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const loading = ref(false)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const topicList = ref([])
const activeTab = ref('basic')
const publishing = ref(false)
const subscribing = ref(false)
const receivedMessages = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  topicName: '',
  topicType: '',
  qosLevel: '',
  status: ''
})

// 表单数据
const form = reactive({
  topicId: '',
  topicName: '',
  topicType: '',
  qosLevel: '0',
  retainMessage: false,
  accessControl: false,
  messageExpiry: 0,
  maxMessageSize: 1024,
  maxSubscribers: 1000,
  messageRateLimit: 0,
  persistent: true,
  compressed: false,
  topicPattern: '',
  extendConfig: '',
  publishPermission: ['admin'],
  subscribePermission: ['admin'],
  ipWhitelist: '',
  clientIdWhitelist: '',
  status: '1',
  description: ''
})

// 对话框
const dialog = reactive({
  visible: false,
  title: ''
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: null
})

// 发布消息对话框
const publishDialog = reactive({
  visible: false
})

// 订阅监听对话框
const subscribeDialog = reactive({
  visible: false
})

// 权限设置对话框
const permissionDialog = reactive({
  visible: false
})

// 发布消息表单
const publishForm = reactive({
  topicName: '',
  qos: '0',
  retain: false,
  messageFormat: 'text',
  message: ''
})

// 订阅表单
const subscribeForm = reactive({
  topicName: '',
  qos: '0'
})

// 权限表单
const permissionForm = reactive({
  topicName: '',
  publishRoles: ['admin'],
  subscribeRoles: ['admin'],
  ipWhitelist: '',
  clientWhitelist: ''
})

// 表单验证规则
const rules = reactive({
  topicName: [{ required: true, message: '主题名称不能为空', trigger: 'blur' }],
  topicType: [{ required: true, message: '主题类型不能为空', trigger: 'change' }],
  qosLevel: [{ required: true, message: 'QoS等级不能为空', trigger: 'change' }]
})

// 获取主题类型图标
const getTopicIcon = (type: string) => {
  switch (type) {
    case 'system': return ChatDotSquare
    case 'device': return Connection
    case 'user': return Bell
    case 'broadcast': return Bell
    default: return ChatDotSquare
  }
}

// 获取主题类型图标颜色
const getTopicIconColor = (type: string) => {
  switch (type) {
    case 'system': return '#409EFF'
    case 'device': return '#67C23A'
    case 'user': return '#E6A23C'
    case 'broadcast': return '#F56C6C'
    default: return '#909399'
  }
}

// 获取主题类型标签样式
const getTopicTypeTag = (type: string) => {
  switch (type) {
    case 'system': return 'primary'
    case 'device': return 'success'
    case 'user': return 'warning'
    case 'broadcast': return 'danger'
    default: return 'info'
  }
}

// 获取主题类型文本
const getTopicTypeText = (type: string) => {
  switch (type) {
    case 'system': return '系统主题'
    case 'device': return '设备主题'
    case 'user': return '用户主题'
    case 'broadcast': return '广播主题'
    default: return '未知'
  }
}

// 获取QoS标签样式
const getQosTag = (qos: string) => {
  switch (qos) {
    case '0': return 'info'
    case '1': return 'warning'
    case '2': return 'danger'
    default: return 'info'
  }
}

// 查询主题列表
const getList = () => {
  loading.value = true
  // 模拟数据
  setTimeout(() => {
    topicList.value = [
      {
        topicId: 'TOPIC001',
        topicName: '/system/device/status',
        topicType: 'system',
        qosLevel: '1',
        subscriberCount: 25,
        messageCount: 1580,
        lastMessageTime: '2024-01-15 14:30:25',
        retainMessage: true,
        accessControl: false,
        status: '1',
        createTime: '2024-01-10 09:00:00',
        updateTime: '2024-01-15 14:30:25',
        description: '设备状态上报系统主题'
      },
      {
        topicId: 'TOPIC002',
        topicName: '/device/sensor/temperature',
        topicType: 'device',
        qosLevel: '0',
        subscriberCount: 18,
        messageCount: 3250,
        lastMessageTime: '2024-01-15 14:28:15',
        retainMessage: false,
        accessControl: true,
        status: '1',
        createTime: '2024-01-10 10:00:00',
        updateTime: '2024-01-15 14:28:15',
        description: '温度传感器数据主题'
      },
      {
        topicId: 'TOPIC003',
        topicName: '/user/notification/alert',
        topicType: 'user',
        qosLevel: '2',
        subscriberCount: 12,
        messageCount: 856,
        lastMessageTime: '2024-01-15 14:25:30',
        retainMessage: true,
        accessControl: true,
        status: '1',
        createTime: '2024-01-10 11:00:00',
        updateTime: '2024-01-15 14:25:30',
        description: '用户告警通知主题'
      },
      {
        topicId: 'TOPIC004',
        topicName: '/broadcast/system/announcement',
        topicType: 'broadcast',
        qosLevel: '1',
        subscriberCount: 45,
        messageCount: 125,
        lastMessageTime: '2024-01-15 12:00:00',
        retainMessage: true,
        accessControl: false,
        status: '0',
        createTime: '2024-01-10 12:00:00',
        updateTime: '2024-01-15 12:00:00',
        description: '系统公告广播主题'
      }
    ]
    total.value = 4
    loading.value = false
  }, 1000)
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.topicName = ''
  queryParams.topicType = ''
  queryParams.qosLevel = ''
  queryParams.status = ''
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.topicId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 状态切换
const handleStatusChange = (row: any) => {
  const text = row.status === '1' ? '启用' : '禁用'
  ElMessageBox.confirm('确认要"' + text + '""' + row.topicName + '"主题吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(text + '成功')
  }).catch(() => {
    row.status = row.status === '1' ? '0' : '1'
  })
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  dialog.visible = true
  dialog.title = '添加主题'
  activeTab.value = 'basic'
}

// 修改按钮操作
const handleUpdate = (row?: any) => {
  reset()
  const topicId = row?.topicId || ids.value[0]
  // 模拟获取详情
  const topic = topicList.value.find(item => item.topicId === topicId)
  if (topic) {
    Object.assign(form, topic)
  }
  dialog.visible = true
  dialog.title = '修改主题'
  activeTab.value = 'basic'
}

// 查看详情
const handleView = (row: any) => {
  detailDialog.data = row
  detailDialog.visible = true
}

// 发布消息
const handlePublish = (row?: any) => {
  const topicId = row?.topicId || ids.value[0]
  const topic = topicList.value.find(item => item.topicId === topicId)
  if (topic) {
    publishForm.topicName = topic.topicName
    publishForm.qos = topic.qosLevel
    publishForm.retain = topic.retainMessage
    publishForm.messageFormat = 'text'
    publishForm.message = ''
    publishDialog.visible = true
  }
}

// 订阅监听
const handleSubscribe = (row?: any) => {
  const topicId = row?.topicId || ids.value[0]
  const topic = topicList.value.find(item => item.topicId === topicId)
  if (topic) {
    subscribeForm.topicName = topic.topicName
    subscribeForm.qos = topic.qosLevel
    receivedMessages.value = []
    subscribeDialog.visible = true
  }
}

// 权限设置
const handlePermission = (row?: any) => {
  const topicId = row?.topicId || ids.value[0]
  const topic = topicList.value.find(item => item.topicId === topicId)
  if (topic) {
    permissionForm.topicName = topic.topicName
    permissionForm.publishRoles = ['admin', 'device']
    permissionForm.subscribeRoles = ['admin', 'device', 'user']
    permissionForm.ipWhitelist = '192.168.1.0/24\n10.0.0.0/8'
    permissionForm.clientWhitelist = 'device_001\ndevice_002\nuser_app'
    permissionDialog.visible = true
  }
}

// 查看订阅者
const viewSubscribers = (row: any) => {
  ElMessage.info('查看订阅者列表：' + row.topicName)
}

// 查看消息历史
const viewMessages = (row: any) => {
  ElMessage.info('查看消息历史：' + row.topicName)
}

// 删除按钮操作
const handleDelete = (row?: any) => {
  const topicIds = row?.topicId ? [row.topicId] : ids.value
  ElMessageBox.confirm('是否确认删除主题编号为"' + topicIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    getList()
  })
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 导入按钮操作
const handleImport = () => {
  ElMessage.info('导入功能开发中')
}

// 发布消息
const publishMessage = () => {
  publishing.value = true
  // 模拟发布过程
  setTimeout(() => {
    ElMessage.success('消息发布成功')
    publishing.value = false
    publishDialog.visible = false
  }, 1500)
}

// 开始订阅
const startSubscribe = () => {
  subscribing.value = true
  ElMessage.success('开始订阅主题：' + subscribeForm.topicName)
  
  // 模拟接收消息
  const messageInterval = setInterval(() => {
    if (!subscribing.value) {
      clearInterval(messageInterval)
      return
    }
    
    const mockMessages = [
      '{"temperature": 25.6, "humidity": 60.2, "timestamp": "' + new Date().toISOString() + '"}',
      '{"status": "online", "battery": 85, "signal": -45}',
      '{"alert": "temperature_high", "value": 35.2, "threshold": 30}',
      '系统公告：设备维护将于今晚22:00开始'
    ]
    
    const randomMessage = mockMessages[Math.floor(Math.random() * mockMessages.length)]
    receivedMessages.value.unshift({
      timestamp: new Date().toLocaleString(),
      qos: subscribeForm.qos,
      retain: Math.random() > 0.8,
      payload: randomMessage
    })
    
    // 限制消息数量
    if (receivedMessages.value.length > 50) {
      receivedMessages.value = receivedMessages.value.slice(0, 50)
    }
  }, 3000)
}

// 停止订阅
const stopSubscribe = () => {
  subscribing.value = false
  ElMessage.info('已停止订阅')
}

// 清空消息
const clearMessages = () => {
  receivedMessages.value = []
  ElMessage.success('消息已清空')
}

// 保存权限
const savePermission = () => {
  ElMessage.success('权限设置保存成功')
  permissionDialog.visible = false
}

// 提交按钮
const submitForm = () => {
  ElMessage.success('操作成功')
  dialog.visible = false
  getList()
}

// 取消按钮
const cancel = () => {
  dialog.visible = false
  reset()
}

// 表单重置
const reset = () => {
  form.topicId = ''
  form.topicName = ''
  form.topicType = ''
  form.qosLevel = '0'
  form.retainMessage = false
  form.accessControl = false
  form.messageExpiry = 0
  form.maxMessageSize = 1024
  form.maxSubscribers = 1000
  form.messageRateLimit = 0
  form.persistent = true
  form.compressed = false
  form.topicPattern = ''
  form.extendConfig = ''
  form.publishPermission = ['admin']
  form.subscribePermission = ['admin']
  form.ipWhitelist = ''
  form.clientIdWhitelist = ''
  form.status = '1'
  form.description = ''
}

// 组件挂载
onMounted(() => {
  getList()
})
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.topic-icon {
  display: flex;
  justify-content: center;
  align-items: center;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.message-list {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.message-item {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.message-time {
  font-size: 12px;
  color: #666;
}

.message-content {
  font-family: 'Courier New', monospace;
  font-size: 13px;
  background: #fff;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  word-break: break-all;
}

.no-messages {
  text-align: center;
  color: #999;
  padding: 20px;
}
</style>